package com.zsc.common.web.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.tbdp.common.model.User;
import com.zsc.common.web.result.Result;
import org.junit.Assert;
import org.junit.Test;

/**
 * JsonUtils.java是互动平台的JSON工具类。
 *
 * @author jason
 * @version 1.0 2017年3月16日
 */
public class JsonUtils {

    /**
     * 序列化配置类对象
     */
    private static final SerializeConfig serializeConfig = new SerializeConfig();

    /**
     * 反序列化配置类对象
     */
    private static final ParserConfig parserConfig = new ParserConfig();

    static {
        serializeConfig.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        parserConfig.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
    }

    public JsonUtils() {
    }

    public static String toJson(Object o) {
        return JSON.toJSONString(o, serializeConfig);
    }

    public static <T> T fromJson(String jsonString, TypeReference<T> clazz) {
        return JSON.parseObject(jsonString, clazz.getType(), parserConfig);
    }

    @Test
    public void testToJson() {
        User user = new User();
        user.setUserId(new Long(1));
        user.setUserTypeId(2);
        System.out.println(toJson(user));
    }

    @Test
    public void testFromJson() {
        String expectJson = "{\"code\": 8200,\"result\": {\"user_id\":1,\"user_type_id\":2}}";
        Result<User> result = fromJson(expectJson, new TypeReference<Result<User>>() {});
        Assert.assertEquals(new Integer(8200), result.getCode());
        Assert.assertEquals(new Long(1), result.getResult().getUserId());
        Assert.assertEquals(new Integer(2), result.getResult().getUserTypeId());
    }
}
